<template>
  <view class="switch" :class="{ 'switch-on': isChecked }" @click="toggle"></view>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  const props = defineProps({
    checked: {
      type: Number,
      default: 0,
    },
    normalBgColor: {
      type: String,
      default: '#dcdcdc',
    },
    activeBgColor: {
      type: String,
      default: '#ff4802',
    },
    sliderColor: {
      type: String,
      default: '#fff',
    },
  });

  const isChecked = ref<Number>(props.checked);
  const emits = defineEmits(['update:checked']);
  const toggle = () => {
    emits('update:checked', isChecked.value ? 0 : 1);
  };

  watch(
    () => props.checked,
    () => {
      isChecked.value = props.checked;
    }
  );
</script>

<style lang="scss" scoped>
  $normalBgColor: v-bind(normalBgColor);
  $activeBgColor: v-bind(activeBgColor);
  $sliderColor: v-bind(sliderColor);

  .switch {
    display: block;
    position: relative;
    width: 94rpx;
    height: 49rpx;
    border-radius: 30rpx;
    box-sizing: border-box;
  }
  .switch:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 94rpx;
    height: 49rpx;
    border-radius: 50rpx;
    background-color: $normalBgColor;
  }
  .switch:after {
    content: ' ';
    position: absolute;
    top: 5rpx;
    left: 4rpx;
    width: 42rpx;
    height: 42rpx;
    border-radius: 50%;
    background-color: $sliderColor;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
    transition: transform 0.35s cubic-bezier(0.4, 0.4, 0.25, 1.35);
  }
  .switch-on:before {
    background-color: $activeBgColor;
  }
  .switch-on:after {
    transform: translateX(45rpx);
  }
</style>
